import time
import traceback
import pandas as pd
from contextlib import contextmanager
from pyvirtualdisplay import Display
from selenium.webdriver.common.keys import Keys
from selenium import webdriver
from selenium.webdriver import FirefoxOptions
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait


@contextmanager
def firefox_brower(url):
    driver = None
    # display = None
    for _ in range(5):
        try:
            # Set screen resolution to 1366 x 768 like most 15" laptops
            display = Display(visible=0, size=(1366, 768))
            display.start()
            opts = FirefoxOptions()
            opts.add_argument('–headless')
            driver = webdriver.Firefox(options=opts)
            # driver.set_window_size(1366, 768)
            time.sleep(3)
            driver.get(url)
            yield driver
            break
        except Exception as e:
            print(traceback.format_exc())
        finally:
            if driver is not None:
                driver.quit()
            if display is not None:
                # quit Xvfb display
                display.stop()


def CHIP_WINNER(ts_code):
    winner_rate = None
    ts_code_split = ts_code.split('.')
    ts_code_ch = str(ts_code_split[1]).lower() + ts_code_split[0]
    url = "http://quote.eastmoney.com/concept/%s.html" % ts_code_ch
    with firefox_brower(url) as driver:
        for _ in range(3):
            try:
                #打印页面标题“百度一下你就知道”
                # print(driver.title)
                #生成当前页面快照
                time.sleep(5)
                # driver.save_screenshot("dongfang.png")
                # id="kw"是百度搜索框，输入字符串“微博”，跳转到搜索中国页面
                # driver.find_element_by_xpath('//*[@id="cmfb-btn"]').click()
                for _ in range(10):
                    try:
                        driver.find_element(by=By.XPATH, value='//*[@id="cmfb-btn"]').click()
                        break
                    except Exception as e:
                        print(traceback.format_exc())
                        time.sleep(3)
                time.sleep(5)
                # bb = driver.find_element_by_xpath('/html/body/div[1]/div[1]/div[3]/div[1]/div[2]/div[3]/div[1]/div[2]/div[2]/div[1]/div[3]/div[2]')
                # cc = driver.find_element_by_xpath('/html/body/div[1]/div[1]/div[3]/div[1]/div[2]/div[3]/div[1]/div[2]/div[2]/div[1]/div[3]/div[1]/label')
                # dd = driver.find_element_by_xpath('/html/body/div[1]/div[1]/div[3]/div[1]/div[2]/div[3]/div[1]/div[2]/div[2]/div[1]/div[3]/div[2]/label')
                span_xpath = '/html/body/div[1]/div[1]/div[3]/div[1]/div[2]/div[3]/div[1]/div[2]/div[2]/div[1]/div[3]/div[2]/span'
                winner_rate_span = None
                for _ in range(10):
                    try:
                        # winner_rate_span = driver.find_element_by_xpath(span_xpath)
                        winner_rate_span = driver.find_element(by=By.XPATH, value=span_xpath)
                        if winner_rate_span is not None:
                            break
                    except Exception as e:
                        print(e)
                        time.sleep(3)
                if winner_rate_span is not None:
                    winner_rate = eval(str(winner_rate_span.text).strip().replace('%', ''))
                if winner_rate is not None:
                    break
            except Exception as e:
                print(traceback.format_exc())
                print('retry times %s' % _)
                continue
    if winner_rate is None:
        winner_rate = 0
    winner_rate_series = pd.Series([winner_rate], name='winner_rate')
    return winner_rate_series



